package org.example.algorithm;

import java.util.Stack;

public class IsValidBracketSolution {
    public static void main(String[] args) {
        String input = "(){}}{";
        System.out.println(isValid(input));

    }

    public static boolean isValid(String s) {
        if (s == null || s.isEmpty() || (s.length() % 2 == 1)) {
            return false;
        }
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
                stack.push(s.charAt(i));
                continue;
            }
            if (stack.isEmpty()) {
                return false;
            } else {
                Character needMatch = stack.pop();
                if ((needMatch == '[' && s.charAt(i) == ']')
                || (needMatch == '{' && s.charAt(i) == '}')
                || (needMatch == '(' && s.charAt(i) == ')')) {
                    continue;
                }
                return false;
            }
        }
        return stack.isEmpty();
    }
}
